﻿namespace Wolfpack.Contrib.Startup.MacAddresses
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.NetworkInformation;
    using Wolfpack.Core;
    using Wolfpack.Core.Interfaces;
    using Wolfpack.Core.Interfaces.Entities;

    public class MacAddressConfig : PluginConfigBase
    {

    }

    public class MacAddress: IStartupPlugin, ICanBeSwitchedOff
    {
        protected readonly MacAddressConfig myConfig;
        public AgentConfiguration myAgent;

        public MacAddress(MacAddressConfig config, AgentConfiguration agent)
        {
            myConfig = config;
            myAgent = agent;
        }

        public MacAddress(MacAddressConfig config)
        {

            myConfig = config;
        }

        public void Initialise()
        {
            if (!Enabled)
            {
                return;
            }

            // varchar(12)
            myAgent.Latitude = ShowNetworkInterfaces();
            myAgent.Longitude = String.Empty;
        }

        public bool Enabled
        {
            get
            {
                return myConfig.Enabled;
            }
            set
            {
                myConfig.Enabled = value;
            }
        }

        public Status Status {get; set; }

        public PluginDescriptor Identity
        {
            get
            {
                return new PluginDescriptor
                {
                    Description = "Add mac address to Latitude field.",
                    Name = "MacAddress",
                    TypeId = new Guid("EB823350-813E-4026-A19F-3D15291BFF6F")
                };
            }
        }

        public void Execute()
        {
        }

        public static string ShowNetworkInterfaces()
        {
            IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            List<string> nicList = new List<string>();

            foreach (NetworkInterface adapter in nics)
            {
                IPInterfaceProperties properties = adapter.GetIPProperties(); //  .GetIPInterfaceProperties();
                PhysicalAddress address = adapter.GetPhysicalAddress();       // mac address.
                if (address.GetAddressBytes().Length > 0)
                {
                    if (adapter.OperationalStatus == OperationalStatus.Up)
                    {
                        nicList.Add(address.ToString());
                    }
                }
            }

            if (nics == null || nics.Length < 1 || nicList.Count == 0)
            {
                return "None found.";
            }

            nicList.Sort();
            return nicList.First().Replace("{", String.Empty).Replace("}", String.Empty);
        }

    }
}
